package com.cskaoyan.service;

import com.cskaoyan.bean.PO.*;
import com.cskaoyan.bean.VO.*;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @author wenkaikai
 * @since 2022/08/17 08:52
 */
@Service
@Transactional
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;

    @Autowired
    MarketBrandMapper marketBrandMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketIssueMapper marketIssueMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    /**
     * 商品总数
     *
     * @return
     */
    @Override
    public long countGoodsNum() {
        long goodsNum = marketGoodsMapper.countByExample(null);
        return goodsNum;
    }

    /**
     * 商品类目，查询三个，父类目、当前类目、兄弟类目
     *
     * @param id
     * @return
     */
    @Override
    public WxCategoryVO queryCategoryById(Integer id) {
        // 查当前类目
        MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(id);
        // 查找父类目
        Integer pid = marketCategory.getPid();
        MarketCategory parentCategory = marketCategoryMapper.selectByPrimaryKey(pid);
        // 找兄弟类目，通过父类id为同一个，查找兄弟
        // 不用分页，不用排序
        MarketCategoryExample example = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = example.createCriteria();
        if (pid != null) {
            criteria.andPidEqualTo(pid);
        }
        // 兄弟类目
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(example);
        // 放进返回类
        WxCategoryVO wxCategoryVO = new WxCategoryVO();
        wxCategoryVO.setBrotherCategory(marketCategories);
        wxCategoryVO.setCurrentCategory(marketCategory);
        wxCategoryVO.setParentCategory(parentCategory);
        return wxCategoryVO;
    }

    /*
     商品list
     */
    @Override
    public WxGoodsListVO2 queryGoodsList(BasePageInfo info, Boolean isHot, Boolean isNew, Integer brandId, Integer categoryId) {
        MarketGoodsExample example = new MarketGoodsExample();
        // 都不为空，拼接上order by 条件
        if (info.getSort() != null && info.getOrder() != null) {
            example.setOrderByClause(info.getSort() + " " + info.getOrder());
        }
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        // 不为空，拼接上查询条件
        if (isNew != null) {
            criteria.andIsNewEqualTo(isNew);
        }
        if (isHot != null) {
            criteria.andIsHotEqualTo(isHot);
        }
        if (brandId != null && !"".equals(brandId)) {
            criteria.andBrandIdEqualTo(brandId);
        }
        if (categoryId != null && !"".equals(categoryId)) {
            if (categoryId.intValue() != 0) {
                // 等于0是新品，热点商品
                criteria.andCategoryIdEqualTo(categoryId);
            }
        }
        // 查询前开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());
        List<MarketGoodsVo> marketGoodsVos = marketGoodsMapper.selectByExampleVo(example);
        // 查询结果交给分页工具处理
        PageInfo<MarketGoodsVo> marketGoodsVoPageInfo = new PageInfo<>(marketGoodsVos);


        // 查找筛选后的类目列表 ，二级类目 且sortorder优先级高的
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
        categoryExampleCriteria.andLevelEqualTo("L2");
        categoryExampleCriteria.andSortOrderLessThan((byte) 5);
        PageHelper.startPage(info.getPage(), info.getLimit());
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(categoryExample);
        PageInfo<MarketCategory> marketCategoryPageInfo = new PageInfo<>(marketCategories);

        WxGoodsListVO2 wxGoodsListVO = new WxGoodsListVO2();
        wxGoodsListVO.setFilterCategoryList(marketCategoryPageInfo.getList());
        wxGoodsListVO.setLimit(marketGoodsVoPageInfo.getPageSize());
        wxGoodsListVO.setPage(marketGoodsVoPageInfo.getPageNum());
        wxGoodsListVO.setPages(marketGoodsVoPageInfo.getPages());
        wxGoodsListVO.setTotal((int) marketGoodsVoPageInfo.getTotal());
        List<MarketGoodsVo> marketGoodsVoList = marketGoodsVoPageInfo.getList();
        ArrayList<WxHomeIndexGoodsVO> goodsList = new ArrayList<>();
        for (MarketGoodsVo marketGoodsVo : marketGoodsVoList) {
            goodsList.add(new WxHomeIndexGoodsVO(marketGoodsVo.getId(), marketGoodsVo.getIsHot(),
                    marketGoodsVo.getIsNew(), marketGoodsVo.getName(), marketGoodsVo.getPicUrl(),
                    marketGoodsVo.getBrief(), marketGoodsVo.getCounterPrice(), marketGoodsVo.getRetailPrice()));
        }
        wxGoodsListVO.setList(goodsList);
        return wxGoodsListVO;

    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @Override
    public WxGoodsDetailVO queryGoodsDetail(Integer id) {
        WxGoodsDetailVO data = new WxGoodsDetailVO();
        // 先查商品
        MarketGoodsVo marketGoods = marketGoodsMapper.selectByPrimaryKeyVo(id);
        data.setInfo(marketGoods);

        // 查attribute
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria attributeExampleCriteria = marketGoodsAttributeExample.createCriteria();
        attributeExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> marketGoodsAttributes = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        data.setAttribute(marketGoodsAttributes);

        // 查品牌
        MarketBrand marketBrand = marketBrandMapper.selectByPrimaryKey(marketGoods.getBrandId());
        data.setBrand(marketBrand);

        // 查评论
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria commentExampleCriteria = marketCommentExample.createCriteria();
        commentExampleCriteria.andTypeEqualTo((byte) 0);
        commentExampleCriteria.andValueIdEqualTo(id);
        List<MarketComment> marketComments = marketCommentMapper.selectByExample(marketCommentExample);
        WxGoodsDetailCommentVO goodsDetailCommentVO = new WxGoodsDetailCommentVO();
        goodsDetailCommentVO.setCount((long) marketComments.size());
        int commentViewNum = 1;
        List<MarketComment> marketCommentView = new ArrayList<>();
        for (MarketComment marketComment : marketComments) {
            if (commentViewNum > 3) {
                break;
            }
            marketCommentView.add(marketComment);
            commentViewNum++;
        }
        // for (MarketComment marketComment : marketComments) {
        //     if (commentViewNum > 3) {
        //         break;
        //     }
        //     marketCommentView.add(marketComment);
        //     commentViewNum++;
        // }
        goodsDetailCommentVO.setData(marketCommentView);
        data.setComment(goodsDetailCommentVO);

        // 查团购,不好查不查直接返回空数组
        ArrayList<MarketGroupon> marketGroupons = new ArrayList<>();
        data.setGroupon(marketGroupons);

        // 查问题issue,要详细就，设置example条件为逻辑删除false
        List<MarketIssue> marketIssues = marketIssueMapper.selectByExample(null);
        data.setIssue(marketIssues);

        // 查商品货品表
        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria productExampleCriteria = goodsProductExample.createCriteria();
        productExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(goodsProductExample);
        data.setProductList(marketGoodsProducts);

        // 查分享海报，都是true，但是url都素空的
        data.setShare(true);
        data.setShareImage(marketGoods.getShareUrl());

        // 查规格表
        MarketGoodsSpecificationExample goodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria specificationExampleCriteria = goodsSpecificationExample.createCriteria();
        specificationExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> marketGoodsSpecifications = marketGoodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        ArrayList<WxGoodsSpecificationInnerVO> specificationList = new ArrayList<>();
        if (marketGoodsSpecifications == null) {
            data.setSpecificationList(specificationList);
        }

        HashSet<String> nameSet = new LinkedHashSet<>();
        for (MarketGoodsSpecification specification : marketGoodsSpecifications) {
            // 获得规格名,再分组
            nameSet.add(specification.getSpecification());
        }
        for (String s : nameSet) {
            WxGoodsSpecificationInnerVO wxGoodsSpecificationInnerVO = new WxGoodsSpecificationInnerVO();
            wxGoodsSpecificationInnerVO.setName(s);
            ArrayList<MarketGoodsSpecification> goodsSpecifications = new ArrayList<>();
            for (MarketGoodsSpecification specification : marketGoodsSpecifications) {
                if (specification.getSpecification().equals(s)) {
                    goodsSpecifications.add(specification);
                }
            }
            wxGoodsSpecificationInnerVO.setValueList(goodsSpecifications);
            specificationList.add(wxGoodsSpecificationInnerVO);
        }
        data.setSpecificationList(specificationList);

        // 查用户是否收藏 ,这里要查登入状态，再根据用户的id和商品的id，查收藏表，若查到数据
        // 则显示1，查到空，则显示0
        data.setUserHasCollect(0);
        return data;
    }


    /**
     * 查询此商品的相关商品
     * 就是同类目下的兄弟商品
     *
     * @return
     */
    @Override
    public CommonData<WxHomeIndexGoodsVO> queryRelatedGoods(Integer id) {
        // 先查询categories
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        Integer categoryId = marketGoods.getCategoryId();
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        // 只找其中的一页的6个数据
        PageHelper.startPage(1, 6);
        List<MarketGoods> relatedGoodsList = marketGoodsMapper.selectByExample(marketGoodsExample);
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(relatedGoodsList);
        CommonData<WxHomeIndexGoodsVO> data = new CommonData<>();
        data.setLimit(marketGoodsPageInfo.getPageSize());
        data.setPage(marketGoodsPageInfo.getPageNum());
        data.setPages(marketGoodsPageInfo.getPages());
        data.setTotal((int) marketGoodsPageInfo.getTotal());
        ArrayList<WxHomeIndexGoodsVO> indexGoodsVOS = new ArrayList<>();
        for (MarketGoods goods : marketGoodsPageInfo.getList()) {
            indexGoodsVOS.add(new WxHomeIndexGoodsVO(goods.getId(), goods.getIsHot(), goods.getIsNew(),
                    goods.getName(), goods.getPicUrl(), goods.getBrief(), goods.getCounterPrice(), goods.getRetailPrice()));
        }
        data.setList(indexGoodsVOS);
        return data;

    }
}